物件 在 JS 是十分重要的,並且關於物件有幾個滿重要的特性:
不過在這之前先來介紹物件基礎概念及操作 (混文章)
物件是有以下東西組成的:
{} 一般稱作物件實字 (Object Literals)。屬性(property) /  值(value) 組成。而物件的值可以是任何純值、陣列、物件本身以及函式:
var school = {
	name:'Taipei University',
	age:45,
	vacation:true,
  teacher:['Mike','Lisha','Bob'],
	classes: {
		student:['Kevin','Clara','Rose'],
	},
	broadcast:function(){
		console.log('學校廣播');
	}
}
在 JS有兩種方法可以獲得物件中的值:
. 點運算子[]
var school = {
	name:'Taipei University',
	age:45,
	vacation:true,
  teacher:['Mike','Lisha','Bob'],
	classes: {
		student:['Kevin','Clara','Rose'],
	},
	broadcast:function(){
		console.log('學校廣播');
	}
}
school.name //Taipei University
school['age'] //45
使用 [] 方法取值,有個好處,是可以透過變數替換 [] 中的值,來取出物件中不同的值,也就是:
var school = {
	name:'Taipei University',
	age:45,
	vacation:true,
  teacher:['Mike','Lisha','Bob'],
	classes: {
		student:['Kevin','Clara','Rose'],
	},
	broadcast:function(){
		console.log('學校廣播');
	}
}
var test ='name'
console.log(school[test]) // Taipei University
test = 'age'
console.log(school[test]) // 45
而這個特性 使用 .  運算子,便無法達成了,按照上面範例使用  school.test  他會回傳 undefined 。
值得一題的是物件中的屬性都會是字串,當屬性不是字串時, JS 會自動將物件屬性強制轉成字串,因此我們實際上在建立物件時,通常會直接忽略屬性要寫成字串這點。
也因此物件屬性是能添加某些特殊符號,不過是只能使用 [] 來取值的,而 . 運算子則無法正確使用。
var obj= {
	'obj-test':'測試文字'
}
obj.obj-test // test is not defined
obj['obj-test'] //測試文字
實際上若要在物件新增屬性,方法就跟物件取值一樣使用 . 運算子或是 [] 指向新屬性,接著再使用 =  為該屬性賦值。
var school = {
	name:'Taipei University',
	age:45,
	vacation:true,
  teacher:['Mike','Lisha','Bob'],
	classes: {
		student:['Kevin','Clara','Rose'],
	},
	broadcast:function(){
		console.log('學校廣播');
	}
}
school.phoneNumber = '02-4050331'
school['address'] = '台北市中正區北平西路3號'
console.log(school.phoneNumber,school['address']) // '02-4050331' , '台北市中正區北平西路3號'
要刪除屬性也很簡單,直接使用一元運算子 delete 再使用 . 或 [] 指向要刪除的屬性。
var school = {
	name:'Taipei University',
	age:45,
	vacation:true,
  teacher:['Mike','Lisha','Bob'],
	classes: {
		student:['Kevin','Clara','Rose'],
	},
	broadcast:function(){
		console.log('學校廣播');
	}
}
delete school.age
console.log(school.age) //undefined
上面有提到物件中也能使用函式,正確的寫法會是
var school = {
	broadcast:function(){
		console.log('學校廣播');
	}
}
school.broadcast() // 學校廣播
而 ES6 則為物件函式提供了縮寫,可以省略  :function 直接寫成 :
var school = {
	broadcast(){
		console.log('學校廣播');
	}
}
school.broadcast() // 學校廣播
在使用一些大型框架時會很常看到這個縮寫方法。